<template>
  <div class="user-profile" @click="toggleDropdown">
    <!-- 未登录时显示默认头像和文字 -->
    <div v-if="!user.isLoggedIn" class="avatar-placeholder">
      <i class="fas fa-user"></i>
      <span>未登录</span>
    </div>
    <!-- 已登录时显示用户头像 -->
    <img v-else :src="user.avatar" :alt="user.name" class="avatar">
    
    <dropdown-menu 
      v-if="showDropdown" 
      :user="user"
      @login="$emit('login')"
      @logout="$emit('logout')"
      @view-orders="$emit('view-orders')"
      @view-profile="$emit('view-profile')">
    </dropdown-menu>
  </div>
</template>

<script>
import DropdownMenu from './DropdownMenu.vue'

export default {
  name: 'UserProfile',
  components: {
    DropdownMenu
  },
  props: {
    user: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      showDropdown: false
    }
  },
  methods: {
    toggleDropdown(event) {
      event.stopPropagation()
      this.showDropdown = !this.showDropdown
      if (this.showDropdown) {
        document.addEventListener('click', this.closeDropdown)
      } else {
        document.removeEventListener('click', this.closeDropdown)
      }
    },
    closeDropdown() {
      this.showDropdown = false
      document.removeEventListener('click', this.closeDropdown)
    }
  },
  beforeUnmount() {
    document.removeEventListener('click', this.closeDropdown)
  },
  emits: ['login', 'logout', 'view-orders', 'view-profile']
}
</script>

<style scoped>
.user-profile {
  position: relative;
  cursor: pointer;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid white;
  transition: border-color 0.3s;
}

.avatar-placeholder {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  color: white;
  font-size: 14px;
}

.avatar-placeholder i {
  font-size: 16px;
}

.user-profile:hover .avatar {
  border-color: var(--accent-color);
}

.user-profile:hover .avatar-placeholder {
  background: rgba(255, 255, 255, 0.3);
}
</style>